package com.guoxue.util;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Component;

import javapns.devices.Device;
import javapns.devices.implementations.basic.BasicDevice;
import javapns.notification.AppleNotificationServerBasicImpl;
import javapns.notification.PushNotificationManager;
import javapns.notification.PushNotificationPayload;
import javapns.notification.PushedNotification;
@Component
public class PushUtil {
	
	/**
	 * IOS消息推送
	 * @param tokens IOS唯一设备标识
	 * @param message 推送消息内容,不能超过256个字节
	 * @param sendSingle 单个设备，单个消息发送
	 * @param deviceToken IOS唯一设备标识(单个)
	 */
	public void sendPush(List<String> tokens,String message,boolean sendSingle,String deviceToken) {
		try {
			System.out.println("zsl==========开始推送消息");
			PushNotificationPayload payload = new PushNotificationPayload();
			payload.addAlert(message); // 消息内容
			payload.addBadge(1);
			payload.addSound("default");
			PushNotificationManager pushManager = new PushNotificationManager();
			// true：表示的是产品测试推送服务 false：表示的是产品发布推送服务
			String certificatePath = this.getClass().getResource("/").getPath()+"Push/push.p12";
			System.out.println(certificatePath);
			pushManager.initializeConnection(new AppleNotificationServerBasicImpl(certificatePath, "liang1993", false));
			List<PushedNotification> notifications = new ArrayList<PushedNotification>();
			// 开始推送消息
			if (sendSingle) {
				Device device = new BasicDevice();
				device.setToken(deviceToken);
				PushedNotification notification = pushManager.sendNotification(device, payload, true);
				notifications.add(notification);
			} else {
				List<Device> devices = new ArrayList<Device>();
				for (String token : tokens) {
					devices.add(new BasicDevice(token));
				}
				notifications = pushManager.sendNotifications(payload, devices);
			}
			List<PushedNotification> failedNotification = PushedNotification.findFailedNotifications(notifications);
			List<PushedNotification> successfulNotification = PushedNotification.findSuccessfulNotifications(notifications);
			int failed = failedNotification.size();
			int successful = successfulNotification.size();
			System.out.println("zsl==========成功数：" + successful);
			System.out.println("zsl==========失败数：" + failed);
			pushManager.stopConnection();
			System.out.println("zsl==========消息推送完毕");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
